package com.motu.vertx.module.utility.logsdk;

import com.motu.data.UserLoginDevice;
import com.motu.vertx.module.utility.base.BaseServerParam;
import com.motu.vertx.module.utility.commondata.CommonDataManager;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ReyunManager {
	private static final Logger logger = LoggerFactory.getLogger(ReyunManager.class);

	// 事件名称
	public static final String EVENT_REGISTER = "register";//注册事件
	public static final String EVENT_LOGIN = "loggedin";//登录事件
	public static final String EVENT_CHARGE = "payment";//充值事件

	/**
	 * 获取公共参数
	 *
	 * @param context         事件参数
	 * @param eventName       事件名称
	 * @param userId          用户ID
	 * @param userLoginDevice 用户登录设备信息
	 * @return 上报公共参数
	 */
	private static JsonObject getCommonParams(JsonObject context, String eventName, long userId, UserLoginDevice userLoginDevice) {
		try {
			if (userLoginDevice == null) {
				logger.error("ReyunManager send error loginDeviceInfo is null userId:{} eventName:{}", userId, eventName);
				return null;
			}

			// 获取应用包appKey
			ChargePackage chargePackage = CommonDataManager.getChargePackage(ChargePackage.TYPE_REYUN, userLoginDevice.getPlatform(), userLoginDevice.getChannel());
			if (chargePackage == null || !chargePackage.hasReyunKey()) {
				return null;
			}
			String appKey = chargePackage.getReyunKey();

			// 必须是ios或Android设备
			if (!userLoginDevice.getRyos().equalsIgnoreCase("ios") && !userLoginDevice.getRyos().equalsIgnoreCase("android")) {
				logger.error("ReyunManager send error userId:{} ryos:{}", userId, userLoginDevice.getRyos());
				return null;
			}

			context.put("_ip", userLoginDevice.getIp());
			context.put("_tz", "+8");// 固定+8
			context.put("_ryos", userLoginDevice.getRyos());//操作系统
			context.put("_ryosversion", userLoginDevice.getRyosVersion());//操作系统版本
			context.put("_app_version", userLoginDevice.getAppVersion());//app版本
			context.put("_lib_version", "1.0.0");//api版本，固定1.0.0
			context.put("_timestamp", System.currentTimeMillis());//时间戳（毫秒）
			context.put("_pkgname", userLoginDevice.getPackageName());//包名

			// 热云取设备ID有自己的规则
			if (!Tool.isEmpty(userLoginDevice.getRyDeviceId())) {
				context.put("_deviceid", userLoginDevice.getRyDeviceId());
			} else {
				context.put("_deviceid", userLoginDevice.getDeviceId());
			}

			if (userLoginDevice.getRyos().equalsIgnoreCase("ios")) {
				if (Tool.isEmpty(userLoginDevice.getIdfa())) {
					context.put("_idfa", "00000000-0000-0000-0000-000000000000");// 广告标示符，获取不到传00000000-0000-0000-0000-000000000000
				} else {
					context.put("_idfa", userLoginDevice.getIdfa());
				}
				context.put("_idfv", userLoginDevice.getIdfv());
			} else if (userLoginDevice.getRyos().equalsIgnoreCase("android")) {
				if (Tool.isEmpty(userLoginDevice.getImei())) {
					context.put("_imei", "null");// 获取不到传null
				} else {
					context.put("_imei", userLoginDevice.getImei());
				}
				context.put("_androidid", userLoginDevice.getAndroidId());
				if (Tool.isEmpty(userLoginDevice.getOaid())) {
					context.put("_oaid", "null");// 获取不到传null
				} else {
					context.put("_oaid", userLoginDevice.getOaid());
				}
			}

			JsonObject data = new JsonObject();
			String who = String.valueOf(userId);
			data.put("appid", appKey);
			data.put("who", who);
			data.put("context", context);

			JsonObject obj = new JsonObject().put("type", eventName).put("data", data);
			return obj;
		} catch (Exception e) {
			logger.error("ReyunManager send error Exception:{}", Tool.getException(e));
			return null;
		}
	}

	/***
	 * 登录事件
	 * @param userId 用户ID
	 * @param userLoginDevice 用户登录设备信息
	 */
	public static void sendLoginEvent(long userId, UserLoginDevice userLoginDevice) {
		JsonObject context = new JsonObject();
		JsonObject params = getCommonParams(context, EVENT_LOGIN, userId, userLoginDevice);
		if (params == null) {
			return;
		}
		LogSDKManager.pushToQueue(LogSDKManager.KAFKA_TOPIC_REYUN, params);
	}

	/***
	 * 注册事件
	 * @param userId 用户ID
	 * @param userLoginDevice 用户登录设备信息
	 */
	public static void sendRegisterEvent(long userId, UserLoginDevice userLoginDevice) {
		JsonObject context = new JsonObject();
		JsonObject params = getCommonParams(context, EVENT_REGISTER, userId, userLoginDevice);
		if (params == null) {
			return;
		}

		// 设置事件参数
		context.put("_model", userLoginDevice.getDeviceType());

		LogSDKManager.pushToQueue(LogSDKManager.KAFKA_TOPIC_REYUN, params);
	}

	/***
	 * 充值事件
	 * @param userId 用户ID
	 * @param userLoginDevice 用户登录设备信息
	 * @param orderId 订单id
	 * @param money 付费金额（bi金额，根据货币类型获取，iap.getBiMoney()）
	 * @param userRegisterDay 用户注册天数（发送限制用）
	 */
	public static void sendChargeEvent(long userId, UserLoginDevice userLoginDevice, String orderId, double money, int userRegisterDay) {
		JsonObject context = new JsonObject();
		JsonObject params = getCommonParams(context, EVENT_CHARGE, userId, userLoginDevice);
		if (params == null) {
			return;
		}

		// 设置事件参数
		context.put("_transactionid", orderId);
		context.put("_paymenttype", "unknown");
		context.put("_currencytype", BaseServerParam.LOG_CURRENCY_TYPE);
		context.put("_currencyamount", money);
		context.put("_model", userLoginDevice.getDeviceType());

		LogSDKManager.pushToQueue(LogSDKManager.KAFKA_TOPIC_REYUN, params);
	}

	/***
	 * 发送热云数据-微信小游戏
	 */
	public static void addWxGameLog(String reyunEventType, int platform, long channel, long userId, String openid, Object... params) {
		ChargePackage cp = CommonDataManager.getChargePackage(ChargePackage.TYPE_REYUN, platform, channel);
		if (cp != null && cp.hasReyunKey()) {
			if (Tool.isEmpty(openid)) {
				logger.warn("####  reyun addWxGameLog openid is empty !!! reyunEventType:" + reyunEventType + " userId:" + userId + " openid:" + openid);
				return;
			}

			JsonObject jo = new JsonObject();
			String who = userId + "";
			String when = TimeUtils.getTimeFullStr(TimeUtils.getCurTime());
			JsonObject context = new JsonObject();

			String reyunBaseUrl = "https://log.trackingio.com";
			String urlStr = "";

			context.put("_openid", openid);
//			context.put("_deviceid",openid.toUpperCase());
			context.put("_deviceid", openid);//TODO:热云文档要求转大写,但是 20230921 调试模式出现客户端不一致的情况,热云技术说不强制要求转大写,调试模式下可以和客户端一致,并且正式环境上报也没问题
			context.put("_apptype", "wg");
			context.put("_lib_version", "0.0.0");

			if (reyunEventType.equalsIgnoreCase(NewbiRequestInfo.TYPE_PAYMENT)) {
				urlStr = reyunBaseUrl + "/receive/s2s/payment";
				String orderId = (String) params[0];
				double money = (double) params[1];

				context.put("_transactionid", orderId);
				context.put("_currencyamount", money);
				context.put("_currencytype", "CNY");
				context.put("_paymenttype", "weixinpay");

			} else if (reyunEventType.equalsIgnoreCase(NewbiRequestInfo.TYPE_REGISTER)) {
				urlStr = reyunBaseUrl + "/receive/s2s/register";
//			}else if(info.logType.equalsIgnoreCase(NewbiRequestInfo.TYPE_EVENT )) {
////				urlstr = "http://log.reyun.com/receive/track/event";
			} else if (reyunEventType.equalsIgnoreCase(NewbiRequestInfo.TYPE_LOGIN)) {
				urlStr = reyunBaseUrl + "/receive/s2s/loggedin";

			}
			jo.put("appid", cp.getReyunKey());
			jo.put("who", who);
			jo.put("when", when);
			jo.put("context", context);

			logger.info("####  reyun addWxGameLog reyunEventType:" + reyunEventType + " jo:" + jo.toString());


			JsonObject obj = new JsonObject().put("type", reyunEventType).put("data", jo).put("urlStr", urlStr);
			LogSDKManager.pushToQueue(LogSDKManager.KAFKA_TOPIC_REYUN, obj);
		}
	}

}
